package com.stock.stockana.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.stock.publiclib.model.UserService;
import com.stock.publiclib.utils.DesUtils;
import com.stock.publiclib.utils.StringUtil;
import com.stock.stockana.R;
import com.stock.stockana.StockCenter;
import com.stock.stockana.beans.ResponseBean;
import com.stock.stockana.constants.NetWorkConstants;
import com.stock.stockana.constants.PublicConstants;
import com.stock.stockana.events.network.LoginInEvent;
import com.stock.stockana.requests.LoginIn;

import java.lang.ref.WeakReference;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;

/**
 * Created by ljgsonx on 2016/1/24.
 */
public class SignInActivity extends AppCompatActivity {

    @Bind(R.id.userNameEt)
    EditText userNameEt;
    @Bind(R.id.userPwdEt)
    EditText userPwdEt;
    @Bind(R.id.signin_btn)
    Button signinBtn;
    @Bind(R.id.forgotPwd_btn)
    TextView forgotPwdBtn;
    @Bind(R.id.backToWelcome_btn)
    Button backToWelcomeBtn;

    private final static String TAG = "SignInActivity";
    SignInBtnThread thread;

    SignInHandler mHandler = new SignInHandler(this);

    static class SignInHandler extends Handler {

        WeakReference<SignInActivity> weakReference;

        public SignInHandler(SignInActivity activity) {
            weakReference = new WeakReference<SignInActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            SignInActivity signInActivity = weakReference.get();
            if (null != signInActivity) {
                signInActivity.getSigninBtn().setText(signInActivity.getResources().getString(R.string.user_signIning) + msg.obj);
            }
        }
    }

    public Button getSigninBtn() {
        return signinBtn;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signin_layout);
        ButterKnife.bind(this);
        //沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        configViews();
        EventBus.getDefault().register(this);
    }

    private void configViews() {
        String userName = StockCenter.getUserDB().getUserPhoneNum();
        if (StringUtil.isBlank(userName)) {
            userName = StockCenter.getUserDB().getUserEmail();
            if (!StringUtil.isBlank(userName)) {
                userNameEt.setText(userName);
            }
        } else {
            userNameEt.setText(userName);
        }
        signinBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userName = userNameEt.getText().toString();
                String userPwd = userPwdEt.getText().toString();
                if (StringUtil.hasBlank(userName, userPwd)) {
                    Toast.makeText(SignInActivity.this, "请输入用户名或密码!", Toast.LENGTH_LONG).show();
                } else if (!(userName.contains("@") && userName.contains(".")) && !userName.matches("1[0-9]{10}")) {
                    Toast.makeText(SignInActivity.this, "请输入正确的邮箱或手机号", Toast.LENGTH_LONG).show();
                } else {
                    UserService userService = StockCenter.getUserDB();
                    if (userService == null) {
                        Toast.makeText(SignInActivity.this, "程序发生未知错误,请重启!", Toast.LENGTH_LONG).show();
                        return;
                    }
                    if (userName.contains("@") && userName.contains(".")) {
                        userService.saveUserEmail(userName);
                    } else {
                        userService.saveUserPhoneNum(userName);
                    }
                    LoginIn loginIn = LoginIn.build().setUserNameAndPwd(userName, userPwd);
                    StockCenter.doReq(loginIn);
                    thread = new SignInBtnThread();
                    thread.changeTextofBtn = true;
                    thread.start();
                    signinBtn.setClickable(false);
                }
            }
        });
        backToWelcomeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SignInActivity.this, SignUpActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
            }
        });
    }

    /**
     * Description: 登录响应的UI处理
     * Author: ljgsonx
     * Time: 2016/1/23 18:57
     */
    @Subscribe
    public void onEventMainThread(LoginInEvent event) {
        final ResponseBean rb = event.getmResponseBean();
        if (rb.getRespCode() == NetWorkConstants.RESPONSE_CODE_OK) {
            String accessToken = rb.getAccessToken();
            String uuid = null;
            try {
                String result = new DesUtils(DesUtils.strDefaultKey).decrypt(accessToken);
                String str[] = result.split(",");
                uuid = str[0].trim();
                uuid = uuid.replace("-", "");
                Log.d(TAG, "start registering uuid to JPush:" + uuid);
            } catch (Exception e) {
                Log.d(TAG, "解析access-token出错");
                e.printStackTrace();
            }
            JPushInterface.setAlias(this, uuid, new TagAliasCallback() {
                @Override
                public void gotResult(int i, String s, Set<String> set) {
                    thread.changeTextofBtn = false;
                    signinBtn.setClickable(true);
                    if (i == PublicConstants.JPUSH_RESPONSE_CODE_OK) {
                        Log.d(TAG, "JPush set alias success!");
                        signinBtn.setText("登录成功,正在跳转...");
                        StockCenter.getUserDB().saveToken(rb.getAccessToken());
                        Intent intent = new Intent(SignInActivity.this, MainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
                        finish();
                        return;
                    } else if (i == PublicConstants.JPUSH_RESPONSE_CODE_TIMEOUT) {
                        Log.d(TAG, "JPush set alias timeout");
                    } else {
                        Log.d(TAG, "JPush set alias unknown error:" + i);
                    }
                    signinBtn.setText(getResources().getString(R.string.user_signIn));
                    Toast.makeText(SignInActivity.this, "网络连接错误,请重试!", Toast.LENGTH_LONG).show();
                }
            });
        } else if (rb.getRespCode() == NetWorkConstants.RESPONSE_CODE_NETWORK_ERROR) {
            thread.changeTextofBtn = false;
            signinBtn.setText(getResources().getString(R.string.user_signIn));
            signinBtn.setClickable(true);
            Log.d(TAG, rb.getErrorMsg());
            Toast.makeText(this, "网络连接错误,请检查网络!", Toast.LENGTH_LONG).show();
        } else {
            thread.changeTextofBtn = false;
            signinBtn.setText(getResources().getString(R.string.user_signIn));
            signinBtn.setClickable(true);
            Log.d(TAG, rb.getErrorMsg());
            Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    class SignInBtnThread extends Thread {

        private String dots = " .";
        private boolean changeTextofBtn = true;

        @Override
        public void run() {
            while (changeTextofBtn) {
                Message msg = new Message();
                msg.obj = dots;
                mHandler.sendMessage(msg);
                if (dots.toCharArray().length < 5) {
                    dots = dots + " .";
                } else {
                    dots = "";
                }
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.in_from_left, R.anim.out_from_right);
    }

    /**
     * Description: 设置默认字体
     * Author: ljgsonx
     * Time: 2016/2/24 13:58
     */
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }
}
